<template>
  <div class="statistics-container">
    <a-row :gutter="16">
      <a-col :span="6">
        <a-form-item label="用户ID">
          <a-input-number 
            v-model:value="userId" 
            style="width: 100%" 
            placeholder="请输入用户ID" 
            @change="loadAllData"
          />
        </a-form-item>
      </a-col>
      <a-col :span="6">
        <a-form-item label="时间范围">
          <a-select 
            v-model:value="timeRange" 
            style="width: 100%" 
            @change="loadAllData"
          >
            <a-select-option value="day">今日</a-select-option>
            <a-select-option value="week">本周</a-select-option>
            <a-select-option value="month">本月</a-select-option>
            <a-select-option value="year">本年</a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
    </a-row>

    <!-- 统计卡片 -->
    <a-row :gutter="16" class="stat-cards">
      <a-col :span="4">
        <a-card>
          <statistic
            title="总记录数"
            :value="statisticsData.totalCount || 0"
            :precision="0"
            style="margin-right: 50px"
          >
            <template #prefix>
              <database-outlined />
            </template>
          </statistic>
        </a-card>
      </a-col>
      <a-col :span="4">
        <a-card>
          <statistic
            title="平均血糖"
            :value="statisticsData.avgValue || 0"
            :precision="1"
            :value-style="{ color: getAvgValueColor() }"
          >
            <template #suffix>
              <span>mmol/L</span>
            </template>
          </statistic>
        </a-card>
      </a-col>
      <a-col :span="4">
        <a-card>
          <statistic
            title="最高血糖"
            :value="statisticsData.maxValue || 0"
            :precision="1"
            :value-style="{ color: '#cf1322' }"
          >
            <template #suffix>
              <span>mmol/L</span>
            </template>
          </statistic>
        </a-card>
      </a-col>
      <a-col :span="4">
        <a-card>
          <statistic
            title="最低血糖"
            :value="statisticsData.minValue || 0"
            :precision="1"
            :value-style="{ color: '#3f8600' }"
          >
            <template #suffix>
              <span>mmol/L</span>
            </template>
          </statistic>
        </a-card>
      </a-col>
      <a-col :span="8">
        <a-card>
          <a-row>
            <a-col :span="8">
              <statistic
                title="正常"
                :value="statisticsData.normalCount || 0"
                :precision="0"
                :value-style="{ color: '#52c41a' }"
              />
            </a-col>
            <a-col :span="8">
              <statistic
                title="偏低"
                :value="statisticsData.lowCount || 0"
                :precision="0"
                :value-style="{ color: '#faad14' }"
              />
            </a-col>
            <a-col :span="8">
              <statistic
                title="偏高"
                :value="statisticsData.highCount || 0"
                :precision="0"
                :value-style="{ color: '#f5222d' }"
              />
            </a-col>
          </a-row>
        </a-card>
      </a-col>
    </a-row>

    <!-- 血糖趋势图 -->
    <a-card title="血糖趋势" :bordered="false" class="chart-card">
      <div ref="trendChartRef" style="width: 100%; height: 400px"></div>
    </a-card>

    <!-- 血糖类型分布图 -->
    <a-row :gutter="16" class="chart-row">
      <a-col :span="12">
        <a-card title="各测量类型血糖值对比" :bordered="false" class="chart-card">
          <div ref="typeChartRef" style="width: 100%; height: 400px"></div>
        </a-card>
      </a-col>
      <a-col :span="12">
        <a-card title="血糖状态分布" :bordered="false" class="chart-card">
          <div ref="statusChartRef" style="width: 100%; height: 400px"></div>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue';
import { message, Statistic } from 'ant-design-vue';
import { DatabaseOutlined } from '@ant-design/icons-vue';
import axios from 'axios';
import * as echarts from 'echarts/core';
import { GridComponent, TooltipComponent, TitleComponent, LegendComponent } from 'echarts/components';
import { LineChart, BarChart, PieChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';

// 注册必须的组件
echarts.use([
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent,
  LineChart,
  BarChart,
  PieChart,
  CanvasRenderer
]);

const userId = ref(null);
const timeRange = ref('week');

// 图表引用
const trendChartRef = ref(null);
const typeChartRef = ref(null);
const statusChartRef = ref(null);

// 图表实例
let trendChart = null;
let typeChart = null;
let statusChart = null;

// 统计数据
const statisticsData = reactive({
  totalCount: 0,
  avgValue: 0,
  maxValue: 0,
  minValue: 0,
  normalCount: 0,
  lowCount: 0,
  highCount: 0
});

// 趋势数据
const trendData = ref([]);

// 分类数据
const typeData = ref([]);

// 加载统计数据
const loadStatisticsData = async () => {
  if (!userId.value) return;
  
  try {
    const response = await axios.get('/admin/blood-sugar/statistics', {
      params: {
        userId: userId.value,
        timeRange: timeRange.value
      }
    });
    
    if (response.data.code === 0) {
      Object.assign(statisticsData, response.data.data);
    } else {
      message.error(response.data.message || '获取统计数据失败');
    }
  } catch (error) {
    console.error('获取统计数据错误', error);
    message.error('获取统计数据失败');
  }
};

// 加载趋势数据
const loadTrendData = async () => {
  if (!userId.value) return;
  
  try {
    const response = await axios.get('/admin/blood-sugar/trend', {
      params: {
        userId: userId.value,
        timeRange: timeRange.value
      }
    });
    
    if (response.data.code === 0) {
      trendData.value = response.data.data;
      renderTrendChart();
    } else {
      message.error(response.data.message || '获取趋势数据失败');
    }
  } catch (error) {
    console.error('获取趋势数据错误', error);
    message.error('获取趋势数据失败');
  }
};

// 加载分类数据
const loadTypeData = async () => {
  if (!userId.value) return;
  
  try {
    const response = await axios.get('/admin/blood-sugar/by-measure-type', {
      params: {
        userId: userId.value,
        timeRange: timeRange.value
      }
    });
    
    if (response.data.code === 0) {
      typeData.value = response.data.data;
      renderTypeChart();
      renderStatusChart();
    } else {
      message.error(response.data.message || '获取分类数据失败');
    }
  } catch (error) {
    console.error('获取分类数据错误', error);
    message.error('获取分类数据失败');
  }
};

// 加载所有数据
const loadAllData = () => {
  if (!userId.value) {
    message.warning('请输入用户ID');
    return;
  }
  
  loadStatisticsData();
  loadTrendData();
  loadTypeData();
};

// 渲染血糖趋势图
const renderTrendChart = () => {
  if (!trendChartRef.value) return;
  
  if (!trendChart) {
    trendChart = echarts.init(trendChartRef.value);
  }
  
  const dates = trendData.value.map(item => item.date);
  const values = trendData.value.map(item => item.avgValue);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        const data = params[0];
        return `${data.name}<br/>${data.marker}平均血糖: ${data.value} mmol/L`;
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates
    },
    yAxis: {
      type: 'value',
      name: '血糖值 (mmol/L)',
      axisLabel: {
        formatter: '{value}'
      }
    },
    series: [
      {
        name: '平均血糖',
        type: 'line',
        data: values,
        markLine: {
          data: [
            { 
              name: '正常范围', 
              yAxis: 6.1,
              lineStyle: { color: '#f5222d' } 
            },
            { 
              name: '正常下限', 
              yAxis: 3.9,
              lineStyle: { color: '#faad14' } 
            }
          ],
          label: {
            formatter: '{b}'
          }
        },
        lineStyle: {
          width: 3,
          color: '#1890ff'
        },
        itemStyle: {
          color: '#1890ff'
        },
        smooth: true
      }
    ]
  };
  
  trendChart.setOption(option);
};

// 渲染血糖分类图
const renderTypeChart = () => {
  if (!typeChartRef.value) return;
  
  if (!typeChart) {
    typeChart = echarts.init(typeChartRef.value);
  }
  
  const types = typeData.value.map(item => item.typeName);
  const avgValues = typeData.value.map(item => item.avgValue);
  const counts = typeData.value.map(item => item.count);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['平均血糖', '记录数']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: types
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '血糖值 (mmol/L)',
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '记录数',
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: [
      {
        name: '平均血糖',
        type: 'bar',
        data: avgValues,
        itemStyle: {
          color: '#1890ff'
        }
      },
      {
        name: '记录数',
        type: 'bar',
        yAxisIndex: 1,
        data: counts,
        itemStyle: {
          color: '#52c41a'
        }
      }
    ]
  };
  
  typeChart.setOption(option);
};

// 渲染血糖状态分布图
const renderStatusChart = () => {
  if (!statusChartRef.value) return;
  
  if (!statusChart) {
    statusChart = echarts.init(statusChartRef.value);
  }
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['正常', '偏低', '偏高']
    },
    series: [
      {
        name: '血糖状态',
        type: 'pie',
        radius: '60%',
        center: ['50%', '50%'],
        data: [
          { 
            value: statisticsData.normalCount, 
            name: '正常',
            itemStyle: { color: '#52c41a' }
          },
          { 
            value: statisticsData.lowCount, 
            name: '偏低',
            itemStyle: { color: '#faad14' }
          },
          { 
            value: statisticsData.highCount, 
            name: '偏高',
            itemStyle: { color: '#f5222d' }
          }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          formatter: '{b}: {d}%'
        }
      }
    ]
  };
  
  statusChart.setOption(option);
};

// 获取平均血糖颜色
const getAvgValueColor = () => {
  const avgValue = statisticsData.avgValue;
  if (!avgValue) return '';
  
  if (avgValue < 3.9) {
    return '#faad14'; // 偏低
  } else if (avgValue > 6.1) {
    return '#f5222d'; // 偏高
  } else {
    return '#52c41a'; // 正常
  }
};

// 窗口大小调整时重新渲染图表
const handleResize = () => {
  trendChart?.resize();
  typeChart?.resize();
  statusChart?.resize();
};

// 组件挂载
onMounted(() => {
  window.addEventListener('resize', handleResize);
});

// 组件卸载
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  trendChart?.dispose();
  typeChart?.dispose();
  statusChart?.dispose();
});
</script>

<style scoped>
.statistics-container {
  padding: 24px;
}

.stat-cards {
  margin-bottom: 24px;
}

.chart-card {
  margin-bottom: 24px;
}

.chart-row {
  margin-bottom: 24px;
}
</style>
